<?php
    
    declare (strict_types = 1);
    
    namespace app\controller;
    
    use app\model\Tags as TagsModel;
    
    use app\BaseController;
    use Exception;
    use think\App;
    use think\Request;
    use think\Response;
    
    class Tags extends BaseController
    {
        protected TagsModel $model;
        
        public function __construct(App $app)
        {
            parent::__construct($app);
            $this->model = new TagsModel();
        }
        
        /**
         * 显示资源列表
         *
         * @return Response
         */
        public function list(): Response
        {
            $params = $this->request->param();
            $where  = [];
            if ( !empty($params['title'])) {
                $where[] = ['title', 'like', "%".$params['title']."%",];
            }
            if (isset($params['state']) && $params['state'] !== '') {
                $where[] = ['state', '=', $params['state'],];
            }
            try {
                $query = $this->model->where($where);
                if ( !empty($params['create_time']) && is_array($params['create_time'])) {
                    $query->whereBetweenTime('create_time', $params['create_time'][0], $params['create_time'][1]);
                }
                $count   = $query->count();
                $orderBy = 'id DESC';
                if ( !empty($params['order']) && !empty($params['orderField'])) {
                    $orderBy = $params['orderField']." ".$params['order'];
                }
                $list = $query->page($this->page, $this->pageSize)
                              ->order($orderBy)
                              ->select();
                return $this->success(
                    'success', [
                        'total'    => $count,
                        'page'     => $this->page,
                        'pageSize' => $this->pageSize,
                        'list'     => $list->toArray(),
                    ]
                );
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
        
        /**
         * 获取全部标签列表
         *
         * @return Response
         */
        public function getAll(): Response
        {
            try {
                $data = $this->model
                    ->where('state', TagsModel::STATE_ON_SHELF)
                    ->select();
                if ($data->isEmpty()) {
                    return $this->error('data does not exist');
                }
                $data = $data->map(
                    function ($item) {
                        return [
                            'value' => $item['id'],
                            'label' => $item['title'],
                        ];
                    }
                );
                
                return $this->success('success', $data->toArray());
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
        
        /**
         * 显示创建资源表单页.
         *
         * @return Response
         */
        public function create(): Response
        {
            $params = $this->request->param();
            $info   = $this->model::create($params);
            if ($info->isEmpty()) {
                return $this->error();
            }
            
            return $this->success('success', $info->toArray());
        }
        
        /**
         * 显示指定的资源
         *
         * @param  Request  $request
         *
         * @return Response
         */
        public function read(Request $request): Response
        {
            $id = $request->param('id/d', 0);
            if ( !$id) {
                return $this->error('parameter error');
            }
            try {
                $info = $this->model->find($id);
                if ($info->isEmpty()) {
                    return $this->error('data does not exist');
                }
                
                return $this->success('success', $info->toArray());
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
        
        /**
         * 显示编辑资源表单页.
         *
         * @param  Request  $request
         *
         * @return Response
         */
        public function edit(Request $request): Response
        {
            $params = $request->param();
            if (empty($params['id'])) {
                return $this->error('parameter error');
            }
            try {
                $info = $this->model->find($params['id']);
                if ($info->isEmpty()) {
                    return $this->error('data does not exist');
                }
                if (isset($params['state']) && in_array((int) $params['state'], [0, 1], true)) {
                    $info->state = $params['state'];
                }
                if ( !empty($params['title'])) {
                    $info->title = $params['title'];
                }
                if ( !empty($params['sort'])) {
                    $info->sort = $params['sort'];
                }
                $info->save();
                
                return $this->success('success', $info->toArray());
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
        
        /**
         * 删除指定资源
         *
         * @param  Request  $request
         *
         * @return Response
         */
        public function delete(Request $request): Response
        {
            $id = $request->param('id/d', 0);
            if (empty($id)) {
                return $this->error('parameter error');
            }
            try {
                $result = $this->model::destroy($id);
                if ($result) {
                    return $this->success('success', $id);
                }
                
                return $this->error();
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
        
        /**
         * 批量删除
         *
         * @param  Request  $request
         *
         * @return Response
         */
        public function batchDelete(Request $request): Response
        {
            $ids = $request->param('ids/s', '');
            if (empty($ids)) {
                return $this->error('parameter error');
            }
            $idArr = array_map(
                static function ($id) {
                    return (int) $id;
                }, explode(',', $ids)
            );
            try {
                $result = $this->model::destroy($idArr);
                if ($result) {
                    return $this->success('success', $idArr);
                }
                
                return $this->error();
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
    }
